<template>
  <div>
    <el-row align="middle" class="pt-5">
      <el-col :span="16">
        <p class="main_title">{{ $t("menu.RACE") }}</p>
      </el-col>
    </el-row>

    <div style="display: flex; margin: 15px;0;15px;0">
      <div style="flex: 0 0 85%;padding-right: 5px;padding-left: 5px;" class="mb-4">
        <el-row class="search_block pt-5">
          <el-col :span="2" class="hori-cond"><label class="form-label">来源</label></el-col>
          <el-col :span="3">
            <el-select v-model="searchData.webid" placeholder="全部" @change="doList" clearable filterable>
              <el-option v-for="item in webs" :key="item.webid" :label="item.webname" :value="item.webid">
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="2" class="hori-cond"><label class="form-label">状态</label></el-col>
          <el-col :span="3">
            <el-select v-model="searchData.jobstatus" placeholder="全部" @change="doList" clearable filterable>
              <el-option v-for="item in jobstatuses" :key="item.key" :label="item.value" :value="item.key">
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="2" class="hori-cond" v-if="searchData.jobstatus == 1"><label
              class="form-label">状态</label></el-col>
          <el-col :span="3" v-if="searchData.jobstatus == 1">
            <el-select v-model="searchData.racestatus" placeholder="全部" @change="doList" clearable filterable>
              <el-option v-for="item in racestatuss" :key="item.key" :label="item.value" :value="item.key">
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="2" class="hori-cond" v-if="searchData.jobstatus == 3"><label
              class="form-label">异常</label></el-col>
          <el-col :span="3" v-if="searchData.jobstatus == 3">
            <el-select v-model="searchData.joberror" placeholder="全部" @change="doList" clearable filterable>
              <el-option v-for="item in joberrors" :key="item.key" :label="item.value" :value="item.key">
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="1" class="hori-cond"></el-col>
          <el-col :span="7">
            <el-input placeholder="请输入赛事编号\名称\主办方ID\名称" v-model="searchData.term" class="input-with-select" clearable
              @change="doList">
              <el-button slot="append" icon="el-icon-search" @click="doList">查询</el-button>
            </el-input>
          </el-col>
        </el-row>

        <el-row class="search_block pt-1" style="margin-top: 5px">
          <el-col :span="2" class="hori-cond"><label class="form-label">司放时间</label></el-col>
          <el-col :span="8">
            <el-date-picker style="width: 100%" v-model="searchData.timerange" value-format="yyyy-MM-dd mm:HH:ss"
              type="datetimerange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
              @change="doList"></el-date-picker>
          </el-col>
          <el-col :span="5" class="hori-cond" v-if="searchData.jobstatus == 3"></el-col>
          <el-col :span="1" class="hori-cond"></el-col>
          <el-col :span="7">
            <div style="height: 40px; line-height: 32px">
              <el-checkbox v-model="showInValid" @change="doList">显示无效主办方赛事</el-checkbox>
            </div>
          </el-col>
        </el-row>
      </div>
      <div style="flex: 0 0 15%;padding-right: 5px;padding-left: 5px;" class="mb-4">
        <div style="float:right">
          <el-button size="medium" type="primary" @click="addRace">新增<i
              class="el-icon-circle-plus-outline"></i></el-button>
        </div>
      </div>
    </div>

    <div style="position: sticky">
      <div class="table_container">
        <el-table :data="races" :header-cell-style="boxheader" :row-style="{height:0+'px'}"
          :cell-style="{padding:0+'px'}" style="width: 100%" :height="ELHeight">

          <!-- 展开列 -->
          <el-table-column type="expand">
            <template slot-scope="props">
              <div class="sub-table-container">
                <el-table :data="props.row.race2list" style="width: 100%" empty-text="该比赛暂无多任务">
                  <el-table-column prop="id" label="" width="150"></el-table-column>
                  <el-table-column prop="jobtime" label="任务时间" width="300"></el-table-column>
                  <el-table-column prop="jobstatus" label="状态" width="300">
                    <template slot-scope="scope">
                      <span v-if="scope.row.jobstatus === 0" class="priority_notbegin">未开始</span>
                      <span v-if="scope.row.jobstatus === 1" class="priority_middle">运行中</span>
                      <span v-if="scope.row.jobstatus === 2" class="priority_finished">已完成</span>
                      <el-tooltip placement="right" effect="light">
                        <div slot="content" class="joberror">
                          {{ scope.row.joberror }}
                        </div>
                        <span v-if="scope.row.jobstatus === 3" class="priority_exception"
                          @click="showExp(scope.row.joberror)" style="cursor: pointer">异常终止</span>
                      </el-tooltip>
                      <span v-if="scope.row.jobstatus === 4" class="priority_expired">已过期</span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="hostname" label="主机" width="300"></el-table-column>
                  <el-table-column label="操作" width="300">
                    <template slot-scope="scope">
                      <el-button style="margin-left: 0px !important"
                        v-if="scope.row.jobstatus == 0 || scope.row.jobstatus == 3" type="text"
                        @click="start2(scope.$index, scope.row)">启动
                      </el-button>
                      <el-button style="margin-left: 0px !important" v-if="scope.row.jobstatus == 1" type="text"
                        @click="stop2(scope.$index, scope.row)">停止
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </template>
          </el-table-column>

          <el-table-column min-width="40px" align="center" label="内部/编号" :render-header="renderheader">
            <template slot-scope="scope">
              <span>{{ scope.row.id }}</span>
            </template>
          </el-table-column>
          <el-table-column min-width="75px" align="center" label="页面主办方/名称" :render-header="renderheader">
            <template slot-scope="scope">
              <!--<span>{{ scope.row.orgid }}</span>-->
              <span>{{
                scope.row.orgname === null || scope.row.orgname === undefined
                  ? scope.row.orgid
                  : scope.row.orgname
              }}</span>
            </template>
          </el-table-column>
          <el-table-column min-width="80px" align="center" label="页面比赛/名称" :render-header="renderheader">
            <template slot-scope="scope">
              <el-badge :value="scope.row.racestatus" class="item">
                <span><a @click="goto('spiderlog', scope.row.webid, scope.row.raceid)"
                    style="color: #409eff; cursor: pointer">{{ scope.row.racename }}</a></span>
              </el-badge>
            </template>
          </el-table-column>
          <el-table-column min-width="45px" align="center" label="来源">
            <template slot-scope="scope">
              <span>{{ scope.row.webname }}</span>
            </template>
          </el-table-column>
          <el-table-column min-width="50px" align="center" label="主办方/ID" :render-header="renderheader">
            <template slot-scope="scope">
              <span>{{
                scope.row.orgname === null || scope.row.orgname === undefined
                  ? ""
                  : scope.row.orgid
              }}</span>
            </template>
          </el-table-column>
          <el-table-column min-width="75px" align="center" label="主办方/名称" :render-header="renderheader">
            <template slot-scope="scope">
              <span>{{
                scope.row.orgname === null || scope.row.orgname === undefined
                  ? ""
                  : scope.row.orgname
              }}</span>
            </template>
          </el-table-column>
          <el-table-column min-width="44px" align="center" label="赛事/ID" :render-header="renderheader">
            <template slot-scope="scope">
              <span>{{ scope.row.matchid }}</span>
            </template>
          </el-table-column>
          <el-table-column min-width="44px" align="center" label="分赛/ID" :render-header="renderheader">
            <template slot-scope="scope">
              <span>{{ scope.row.competitionid }}</span>
            </template>
          </el-table-column>
          <el-table-column min-width="90px" align="center" prop="sftime" :label="$t('race.SFTIME')">
            <template slot-scope="scope">
              <span>
                {{(scope.row.sftime||' ').split(" ")[0] }}
                <br />
                {{(scope.row.sftime||' ').split(" ")[1] }}
              </span>
            </template>
          </el-table-column>
          <el-table-column min-width="45px" align="center" :label="$t('race.SFDISTANCE')">
            <template slot-scope="scope">
              <el-badge :value="scope.row.sfdistance == 0 ? '零' : (scope.row.sfdistance > 300 ? '超长' : '')"
                class="item">
                <span>{{ scope.row.sfdistance }}</span>
              </el-badge>
            </template>
          </el-table-column>
          <!-- <el-table-column min-width="80px" align="center" :label="$t('race.LNGLAT')">
            <template slot-scope="scope">
              <span>{{ scope.row.sflng }}/{{ scope.row.sflat }}</span>
            </template>
          </el-table-column> -->
          <el-table-column min-width="76px" align="center" :label="$t('race.STATUS')">
            <template slot-scope="scope">
              <span v-if="scope.row.jobstatus === 0" class="priority_notbegin">{{ $t("status.NOTBEGIN") }}</span>
              <span v-if="scope.row.jobstatus === 1" class="priority_middle">{{
                $t("status.RUNNING")
              }}</span>
              <span v-if="scope.row.jobstatus === 2" class="priority_finished">{{ $t("status.FINISHED") }}</span>
              <el-tooltip placement="right" effect="light">
                <div slot="content" class="joberror">
                  {{ scope.row.joberror }}
                </div>
                <span v-if="scope.row.jobstatus === 3" class="priority_exception" @click="showExp(scope.row.joberror)"
                  style="cursor: pointer">{{ $t("status.EXCEPTION") }}</span>
              </el-tooltip>
              <span v-if="scope.row.jobstatus === 4" class="priority_expired">{{
                $t("status.EXPIRED")
              }}</span>
              <span v-if="scope.row.jobstatus === 5" class="priority_report">{{
                $t("status.REPORT")
              }}</span>
            </template>
          </el-table-column>
          <el-table-column min-width="60px" align="center" label="主机">
            <template slot-scope="scope">
              <span>{{ scope.row.hostname }}</span>
            </template>
          </el-table-column>
          <el-table-column min-width="40px" align="center" :label="$t('race.FLYCOUNT')">
            <template slot-scope="scope">
              <span>{{ scope.row.sffeather }}</span>
            </template>
          </el-table-column>
          <el-table-column min-width="40px" align="center" :label="$t('race.BACKCOUNT')">
            <template slot-scope="scope">
              <span><a @click="goto('raceresult', scope.row.webid, scope.row.raceid)"
                  style="color: #409eff; cursor: pointer">{{ scope.row.amount }}</a></span>
            </template>
          </el-table-column>
          <el-table-column min-width="70px" align="center" label="自动上报">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.reportstatus" :active-value="1" :inactive-value="0"
                @change="changeReport(scope.row)"></el-switch>
            </template>
          </el-table-column>
          <el-table-column min-width="40px" align="center" label="已上报">
            <template slot-scope="scope">
              <span>{{ scope.row.reportnum }}</span>
            </template>
          </el-table-column>
          <el-table-column min-width="130px" align="center" :label="$t('common.OPER')">
            <template slot-scope="scope">
              <el-button type="text" style="margin-left: 0px !important" @click="showDetail(scope.$index, scope.row)">
                {{ $t("common.DETAIL") }}
              </el-button>
              <el-button v-if="
                  scope.row.jobstatus != 2 &&
                  scope.row.jobstatus != 4 &&
                  scope.row.jobstatus != 5
                " style="margin-left: 0px !important" type="text"
                @click="update(scope.$index, scope.row)">{{ $t("common.UPDATE") }}</el-button>
              <el-button style="margin-left: 0px !important" v-if="scope.row.jobstatus == 0 || scope.row.jobstatus == 3"
                type="text" @click="showStart(scope.$index, scope.row)">
                {{ $t("common.START") }}
              </el-button>
              <el-button style="margin-left: 0px !important" v-if="scope.row.jobstatus == 1" type="text"
                @click="stop(scope.$index, scope.row)">
                {{ $t("common.STOP") }}
              </el-button>
              <el-button style="margin-left: 0px !important" v-if="scope.row.jobstatus == 1"
                type="text" @click="showClone(scope.$index, scope.row)">克隆
              </el-button>
              <el-button style="margin-left: 0px !important" v-if="scope.row.jobstatus == 0 || scope.row.jobstatus == 3"
                type="text" @click="deleteResult(scope.$index, scope.row)">
                清理
              </el-button>
              <!-- <a @click="valid(scope.$index, scope.row)" style="color: #409eff; cursor: pointer">校验</a> -->
              <a v-if="scope.row.amount !== 0" @click="downloadList(scope.$index, scope.row)"
                style="color: #409eff; cursor: pointer">下载</a>
            </template>
          </el-table-column>
        </el-table>

        <div class="col-sm pt-3 text-sm-left" style="text-align:right; display: contents">
          <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="searchData.curpage" :page-sizes="[5, 10, 20, 50]" :page-size="searchData.pagesize"
            layout="total, sizes,  pager, jumper" :total="searchData.total">
          </el-pagination>
        </div>
      </div>

      <el-dialog title="校验信息" :visible.sync="validVisible" :width="width" append-to-body>
        <div>
          <div style="margin: 16px; font-size: 16px">
            上报羽数:&nbsp; {{ validData.reportnum }} app羽数:&nbsp;
            {{ validData.count }} &nbsp;&nbsp;&nbsp;&nbsp;
            {{ validData.reportnum == validData.count ? "一致" : "不一致" }}
          </div>
          <div>
            <div style="margin: 16px; font-size: 16px">
              遗漏名次:&nbsp; {{ validData.missing }}
            </div>
          </div>
          <div>
            <div style="margin: 16px; font-size: 16px">
              重复名次:&nbsp; {{ validData.repeat }}
            </div>
          </div>
        </div>
      </el-dialog>

      <el-dialog title="新建比赛" :visible.sync="addVisible" :width="width" :close-on-click-modal="false" append-to-body>
        <img :src="iconImg" class="enlarge" @click="enlarge" width="12px" height="12px" />
        <el-form :model="addform" ref="addform" label-width="120px" :rules="rules">
          <el-form-item label="来源" style="clear: both" prop="webid">
            <el-select v-model="addform.webid" filterable @change="doOrgList">
              <el-option v-for="item in addwebs" :key="item.webid" :label="item.webname" :value="item.webid">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('race.RACENAME')" style="clear: both" prop="racename">
            <el-input v-model="addform.racename" :placeholder="$t('tips.ENTER.RACENAME')"></el-input>
          </el-form-item>
          <el-form-item label="成绩地址" style="clear: both" prop="raceurl">
            <el-row>
              <!-- <el-col :span="16">{{addform.raceurl}}</el-col> -->
              <el-col :span="24">
                <el-input v-model="addform.raceurl"></el-input>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item :label="$t('org.ORGID')" style="clear:both" prop="orgid">
            <el-select v-model="addform.orgid" placeholder="请选择主办方" class="inline" style="width: 100%" clearable
              filterable>
              <el-option v-for="item in orgsels" :key="item.orgid" :label="item.orgid + '_' + item.orgname"
                :value="item.orgid">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('race.SFTIME')" style="clear: both" prop="sftime">
            <el-date-picker v-model="addform.sftime" value-format="yyyy-MM-dd HH:mm:ss" type="datetime"
              style="width: 100%"></el-date-picker>
          </el-form-item>
          <el-form-item :label="$t('race.SFPLACE')" style="clear: both" prop="sfplace">
            <el-input v-model="addform.sfplace" :placeholder="$t('tips.ENTER.SFPLACE')"></el-input>
          </el-form-item>
          <el-form-item label="经纬度" style="clear: both" prop="sflng">
            <el-row>
              <el-col :span="12">
                <el-input v-model="addform.sflng" :placeholder="$t('tips.ENTER.SFLNG')"></el-input>
              </el-col>
              <el-col :span="12">
                <el-input v-model="addform.sflat" :placeholder="$t('tips.ENTER.SFLAT')"></el-input>
              </el-col>
            </el-row>
          </el-form-item>
          <el-row>
            <el-col :span="12">
              <el-form-item :label="$t('race.SFDISTANCE')" style="clear: both" prop="sfdistance">
                <el-input-number type="number" v-model="addform.sfdistance" placeholder="123.45">
                  <template slot="append">KM</template>
                </el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('race.SFFEATHER')" style="clear: both" prop="sffeather">
                <el-input v-model="addform.sffeather" placeholder="200">
                  <template slot="append">羽</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item :label="$t('race.FREQUENCY')" style="clear: both" prop="frequency">
            <el-input v-model="addform.frequency" placeholder="180">
              <template slot="append">秒</template>
            </el-input>
          </el-form-item>
          <el-form-item :label="$t('race.ENDTIME')" style="clear: both" prop="endtime">
            <el-date-picker v-model="addform.endtime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
              :placeholder="$t('tips.ENTER.ENDTIME')" style="width: 100%">
            </el-date-picker>
            <!--<el-input v-model="" :placeholder=""></el-input>-->
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer" style="text-align: center !important">
          <el-button class="cancel_button" @click="addVisible = false">{{ $t("common.CANCEL") }}</el-button>
          <el-button class="confirm_button" @click="addSubmit('addform')">{{ $t("common.CONFIRM2") }}</el-button>
        </span>
      </el-dialog>

      <el-dialog :title="$t('button.UPDATERACE')" :visible.sync="updateVisible" :width="width"
        :close-on-click-modal="false" append-to-body>
        <img :src="iconImg" class="enlarge" @click="enlarge" width="12px" height="12px" />
        <el-form :model="updateform" ref="updateform" label-width="120px" :rules="rules">
          <el-form-item :label="$t('race.RACENAME')" style="clear: both" prop="racename">
            <el-input v-model="updateform.racename" :placeholder="$t('tips.ENTER.RACENAME')"></el-input>
          </el-form-item>
          <el-form-item label="成绩地址" style="clear: both" prop="raceurl">
            <el-input v-model="updateform.raceurl"></el-input>
          </el-form-item>
          <el-form-item :label="$t('race.ORGID')" style="clear: both" prop="orgid">
            <el-input v-model="updateform.orgid" :placeholder="$t('tips.ENTER.ORGID')"></el-input>
          </el-form-item>
          <el-form-item :label="$t('race.SFTIME')" style="clear: both" prop="sftime">
            <el-date-picker v-model="updateform.sftime" value-format="yyyy-MM-dd HH:mm:ss" type="datetime"
              style="width: 100%"></el-date-picker>
          </el-form-item>
          <el-form-item :label="$t('race.SFPLACE')" style="clear: both" prop="sfplace">
            <el-input v-model="updateform.sfplace" :placeholder="$t('tips.ENTER.SFPLACE')"></el-input>
          </el-form-item>
          <el-form-item label="经纬度" style="clear: both" prop="sflng">
            <el-row>
              <el-col :span="12">
                <el-input v-model="updateform.sflng" :placeholder="$t('tips.ENTER.SFLNG')"></el-input>
              </el-col>
              <el-col :span="12">
                <el-input v-model="updateform.sflat" :placeholder="$t('tips.ENTER.SFLAT')"></el-input>
              </el-col>
            </el-row>
          </el-form-item>
          <el-row>
            <el-col :span="12">
              <el-form-item :label="$t('race.SFDISTANCE')" style="clear: both" prop="sfdistance">
                <el-input-number type="number" v-model="updateform.sfdistance" placeholder="123.45">
                  <template slot="append">KM</template>
                </el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('race.SFFEATHER')" style="clear: both" prop="sffeather">
                <el-input v-model="updateform.sffeather" placeholder="200">
                  <template slot="append">羽</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item :label="$t('race.FREQUENCY')" style="clear: both" prop="frequency">
            <el-input v-model="updateform.frequency" placeholder="180">
              <template slot="append">秒</template>
            </el-input>
          </el-form-item>
          <el-form-item :label="$t('race.ENDTIME')" style="clear: both" prop="endtime">
            <el-date-picker v-model="updateform.endtime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
              :placeholder="$t('tips.ENTER.ENDTIME')" style="width: 100%">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="上报羽数" style="clear: both" prop="reportnum">
            <el-input v-model="updateform.reportnum" placeholder="0">
              <template slot="append">羽</template>
            </el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer" style="text-align: center !important">
          <el-button class="cancel_button" @click="updateVisible = false">{{ $t("common.CANCEL") }}</el-button>
          <el-button class="confirm_button" @click="updateSubmit('updateform')">{{ $t("common.CONFIRM2") }}</el-button>
        </span>
      </el-dialog>

      <el-dialog :title="$t('button.DETAILRACE')" :visible.sync="detailVisible" :width="width" append-to-body>
        <img :src="iconImg" class="enlarge" @click="enlarge" width="12px" height="12px" />
        <div class="message-back">
          <el-row class="area-detail">
            <el-col :span="7">
              <span class="define_span">内部编号:</span>
            </el-col>
            <el-col :span="15">
              <span class="define_span" style="text-align: left">{{
                detailRace.id
              }}</span>
            </el-col>
          </el-row>
          <el-row class="area-detail">
            <el-col :span="7">
              <span class="define_span">赛事编号:</span>
            </el-col>
            <el-col :span="15">
              <span class="define_span" style="text-align: left">{{
                detailRace.raceid
              }}</span>
            </el-col>
          </el-row>
          <el-row class="area-detail">
            <el-col :span="7">
              <span class="define_span">{{ $t("race.RACENAME") }}:</span>
            </el-col>
            <el-col :span="15">
              <span class="define_span" style="text-align: left">{{
                detailRace.racename
              }}</span>
            </el-col>
          </el-row>
          <el-row class="area-detail">
            <el-col :span="7">
              <span class="define_span">{{ $t("race.WEBID") }}:</span>
            </el-col>
            <el-col :span="15">
              <span class="define_span" style="text-align: left">{{
                detailRace.webname
              }}</span>
            </el-col>
          </el-row>
          <el-row class="area-detail">
            <el-col :span="7">
              <span class="define_span">{{ $t("race.ORGID") }}:</span>
            </el-col>
            <el-col :span="15">
              <span class="define_span" style="text-align: left">{{
                detailRace.orgid
              }}</span>
            </el-col>
          </el-row>
          <el-row class="area-detail">
            <el-col :span="7">
              <span class="define_span">{{ $t("race.RACETYPE") }}:</span>
            </el-col>
            <el-col :span="15">
              <span class="define_span" style="text-align: left">{{
                detailRace.racetype
              }}</span>
            </el-col>
          </el-row>
          <el-row class="area-detail">
            <el-col :span="7">
              <span class="define_span">司放时间:</span>
            </el-col>
            <el-col :span="15">
              <span class="define_span" style="text-align: left">{{
                detailRace.sftime
              }}</span>
            </el-col>
          </el-row>
          <el-row class="area-detail">
            <el-col :span="7">
              <span class="define_span">{{ $t("race.SFPLACE") }}:</span>
            </el-col>
            <el-col :span="15">
              <span class="define_span" style="text-align: left">{{
                detailRace.sfplace
              }}</span>
            </el-col>
          </el-row>
          <el-row class="area-detail">
            <el-col :span="7">
              <span class="define_span">经纬度:</span>
            </el-col>
            <el-col :span="15">
              <span class="define_span" style="text-align: left">{{ detailRace.sflng }}/{{ detailRace.sflat }}</span>
            </el-col>
          </el-row>
          <el-row class="area-detail">
            <el-col :span="7">
              <span class="define_span">外部系统的赛事id:</span>
            </el-col>
            <el-col :span="15">
              <span class="define_span" style="text-align: left">{{
                detailRace.matchid
              }}</span>
            </el-col>
          </el-row>
          <el-row class="area-detail">
            <el-col :span="7">
              <span class="define_span">外部系统的分赛id:</span>
            </el-col>
            <el-col :span="15">
              <span class="define_span" style="text-align: left">{{
                detailRace.competitionid
              }}</span>
            </el-col>
          </el-row>
          <el-row class="area-detail">
            <el-col :span="7">
              <span class="define_span">{{ $t("race.SFFEATHER") }}:</span>
            </el-col>
            <el-col :span="15">
              <span class="define_span" style="text-align: left">{{
                detailRace.sffeather
              }}</span>
            </el-col>
          </el-row>
        </div>
        <div class="message-task">
          <el-row class="area-detail">
            <el-col :span="7">
              <span class="define_span">比赛URL:</span>
            </el-col>
            <el-col :span="15">
              <span class="define_span" style="text-align: left">{{
                detailRace.raceurl
              }}</span>
            </el-col>
          </el-row>
          <el-row class="area-detail">
            <el-col :span="7">
              <span class="define_span">任务结束时间:</span>
            </el-col>
            <el-col :span="15">
              <span class="define_span" style="text-align: left">{{
                detailRace.endtime
              }}</span>
            </el-col>
          </el-row>
          <el-row class="area-detail">
            <el-col :span="7">
              <span class="define_span">任务心跳时间:</span>
            </el-col>
            <el-col :span="15">
              <span class="define_span" style="text-align: left">{{
                detailRace.jobtime
              }}</span>
            </el-col>
          </el-row>

          <el-row class="area-detail">
            <el-col :span="7">
              <span class="define_span">{{ $t("race.FREQUENCY") }}:</span>
            </el-col>
            <el-col :span="15">
              <span class="define_span" style="text-align: left">{{ detailRace.frequency }} 秒</span>
            </el-col>
          </el-row>
          <el-row class="area-detail">
            <el-col :span="7">
              <span class="define_span">抓取总数:</span>
            </el-col>
            <el-col :span="15">
              <span class="define_span" style="text-align: left">{{
                detailRace.amount
              }}</span>
            </el-col>
          </el-row>
          <el-row class="area-detail">
            <el-col :span="7">
              <span class="define_span">任务状态:</span>
            </el-col>
            <el-col :span="15">
              <span class="define_span" style="text-align: left">{{
                trans(detailRace.jobstatus)
              }}</span>
            </el-col>
          </el-row>
          <el-row class="area-detail">
            <el-col :span="7">
              <span class="define_span">异常日志:</span>
            </el-col>
            <el-col :span="15">
              <span class="define_span" style="text-align: left">{{
                detailRace.joberror
              }}</span>
            </el-col>
          </el-row>
        </div>
      </el-dialog>

      <el-dialog title="错误详情" :visible.sync="expVisible" :width="width" append-to-body>
        <img :src="iconImg" class="enlarge" @click="enlarge" width="12px" height="12px" />
        <textarea rows="20" nz-input v-model="expDetail" style="width: 100% !important"></textarea>
      </el-dialog>

      <el-dialog title="启动：主机选择" :visible.sync="hostVisible" :width="minWidth" append-to-body>
        <img :src="iconImg" class="enlarge" @click="enlarge" width="12px" height="12px" />
        <el-form :model="startform" ref="startform" label-width="120px"">
          <el-form-item label=" 主机" style="clear: both" prop="hostname">
          <el-select v-model="startform.hostname" filterable>
            <el-option v-for="item in hostnames" :key="item.key" :label="item.key" :value="item.value">
            </el-option>
          </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer" style="text-align: center !important">
          <el-button class="cancel_button" @click="hostVisible = false">取消</el-button>
          <el-button class="confirm_button" @click="start('startform')">确定</el-button>
        </span>
      </el-dialog>

      <el-dialog title="克隆：主机选择" :visible.sync="cloneVisible" :width="minWidth" append-to-body>
        <img :src="iconImg" class="enlarge" @click="enlarge" width="12px" height="12px" />
        <el-form :model="cloneform" ref="cloneform" label-width="120px"">
          <el-form-item label=" 主机" style="clear: both" prop="hostname">
          <el-select v-model="cloneform.hostname" filterable>
            <el-option v-for="item in clonenames" :key="item.key" :label="item.key" :value="item.value">
            </el-option>
          </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer" style="text-align: center !important">
          <el-button class="cancel_button" @click="cloneVisible = false">取消</el-button>
          <el-button class="confirm_button" @click="clone('cloneform')">确定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import raceService from "@/service/raceService";
import race2Service from "@/service/race2Service";
import sponsorService from "@/service/sponsorService";
import webService from "@/service/webService";
import enlargeImg from "@/assets/images/icon_2.png";
import narrowImg from "@/assets/images/icon_3.png";
import i18n from "@/lang";

const baseUrl = process.env.BASE_API;
const isDelta = process.env.IS_DELTA;

export default {
  name: "RaceList",
  data() {
    var checkDistance = (rule, value, callback) => {
      setTimeout(() => {
        if (typeof value !== "number") {
          callback(new Error("请输入数字，可以是小数"));
        } else {
          callback();
        }
      }, 50);
    };
    var checkPositiveInteger = (rule, value, callback) => {
      setTimeout(() => {
        if (!new RegExp("^\\d+$").test(value)) {
          callback(new Error("请输入正整数"));
        } else {
          callback();
        }
      }, 50);
    };
    return {
      boxheader: {
        // background: '#eef1f6',
        color: "#606266",
        fontWeight: 800,
        borderBottom: "2px solid #EBEEF5",
      },
      searchData: {
        jobstatus: 1,
        webid: "",
        term: "",
        curpage: 1,
        pagesize: 10,
        timerange: [],
        total: 0,
      },
      showInValid: false,
      races: [],
      iconImg: enlargeImg,
      width: "800px",
      minWidth: "500px",
      ELHeight: 600,
      clientHeight: document.body.clientHeight,
      detailVisible: false,
      detailRace: {},
      validVisible: false,
      validData: {},
      orgsels: [],
      addVisible: false,
      addform: {
        raceid: "",
        racename: "",
        orgid: "",
        webid: 6,
        racetype: "公棚",
        sftime: "",
        sfplace: "",
        sflng: "",
        sflat: "",
        sfdistance: 0,
        sffeather: "",
        raceurl: "",
        frequency: "",
        endtime: "",
      },
      updateVisible: false,
      updateform: {
        id: "",
        racename: "",
        orgid: "",
        webid: "",
        racetype: "",
        sftime: "",
        sfplace: "",
        sflng: "",
        sflat: "",
        sfdistance: 0,
        sffeather: "",
        raceurl: "",
        frequency: "",
        endtime: "",
      },
      sponsors: [],
      webs: [{ webid: "", webname: "全部" }],
      addwebs: [
        // { webid: 2, webname: "安捷" },
        // { webid: 4, webname: "优必胜" },
        // { webid: 6, webname: "凯信" },
        // { webid: 13, webname: "新科汇" },
        // { webid: 88, webname: "其他" },
      ],
      jobstatuses: [
        { key: "", value: i18n.t("status.ALL") },
        { key: 0, value: i18n.t("status.NOTBEGIN") },
        { key: 1, value: i18n.t("status.RUNNING") },
        { key: 2, value: i18n.t("status.FINISHED") },
        { key: 3, value: i18n.t("status.EXCEPTION") },
        { key: 4, value: i18n.t("status.EXPIRED") },
        // {key: 5, value: i18n.t('status.REPORT')}
      ],
      racestatuss: [
        { key: "", value: "全部" },
        { key: "无成绩", value: "无成绩" },
        { key: "中断", value: "中断" },
        // { key: "0空距", value: "0空距" },
        // { key: "超长空距", value: "超长空距" },
      ],
      joberrors: [
        { key: "", value: "全部" },
        { key: "不连续", value: "不连续" },
        { key: "页面失效", value: "页面失效" },
        { key: "Exception", value: "Exception" },
      ],
      rules: {
        racename: [{}],
        sftime: [{}],
        sfplace: [{}],
        sflng: [{}],
        sflat: [{}],
        sfdistance: [{ validator: checkDistance, trigger: "blur" }],
        sffeather: [{ validator: checkPositiveInteger, trigger: "blur" }],
        frequency: [{ validator: checkPositiveInteger, trigger: "blur" }],
        endtime: [{}],
      },
      expVisible: false,
      expDetail: "",
      hostnames: [
        { key: "gugu-match", value: "gugu-match" },
        { key: "gugu-slave", value: "gugu-slave" },
        { key: "gugu-slave2", value: "gugu-slave2" },
        { key: "gugu-slave1", value: "gugu-slave1" },
      ],
      hostVisible: false,
      startform: {
        id: "",
        hostname: "",
      },
      clonenames: [
        { key: "gugu-slave", value: "gugu-slave" },
        { key: "gugu-slave2", value: "gugu-slave2" },
        { key: "gugu-slave1", value: "gugu-slave1" },
      ],
      cloneVisible: false,
      cloneform: {
        id: "",
        hostname: "",
      },
    };
  },
  watch: {},
  mounted: function () {
    this.clientHeight = document.body.clientHeight;
    const that = this;
    window.onresize = function temp() {
      that.clientHeight = document.body.clientHeight;
      that.ELHeight = window.screen.height - 200;
      if (window.screen.height === 900) {
        that.ELHeight = 460;
      }
    };
    // console.log(window.screen.height);
    this.$store.dispatch("setActive", "5").then(() => {
      // this.$root.eventBus.$emit('exit')
    });
    // commit('SET_ACTIVE', 5)
  },
  created() {
    this.ELHeight = window.screen.height - 200;
    if (window.screen.height === 900) {
      this.ELHeight = 460;
    }
    webService
      .listWebs({ status: 0, curpage: 1, pagesize: 9999 })
      .then((res) => {
        if (res && res.data.result === 0) {
          for (let item of res.data.data) {
            this.webs.push(item);
            this.addwebs.push(item);
          }
        }
      });
    if (this.$route.params && this.$route.params.webid) {
      this.searchData.webid = this.$route.params.webid;
      this.searchData.raceid = this.$route.params.raceid;
    }
    this.doList();
  },
  destroyed() {},
  methods: {
    renderheader(h, { column, $index }) {
      return h("span", {}, [
        h("span", {}, column.label.split("/")[0]),
        h("br"),
        h("span", {}, column.label.split("/")[1]),
      ]);
    },
    showExp(data) {
      this.expVisible = true;
      this.expDetail = data;
    },
    showDetail(index, row) {
      raceService.detailRace({ id: row.id }).then((res) => {
        if (res && res.data.result === 0) {
          this.detailRace = res.data.data;
        }
      });
      this.detailVisible = true;
    },
    showStart(index, row) {
      this.startform.id = row.id;
      this.startform.hostname = row.hostname;
      this.hostVisible = true;
    },
    start(startform) {
      raceService.resumeRace(this.startform).then((res) => {
        if (res === null || res === undefined || res === "") {
          this.listRace();
        } else {
          if (res && res.data.result === 0) {
            this.$message({
              message: "启动任务成功",
              type: "success",
            });
          }
          this.listRace();
        }
        this.hostVisible = false;
      });
    },
    stop(index, row) {
      let dataInfo = {
        id: row.id,
      };
      raceService.stopRace(dataInfo).then((res) => {
        if (res && res.data.result === 0) {
          this.$message({
            message: "任务停止成功",
            type: "success",
          });
        }
        this.listRace();
      });
    },
    showClone(index, row) {
      this.cloneform.id = row.id;
      this.cloneform.hostname = row.hostname;
      this.cloneVisible = true;
    },
    clone(cloneform) {
      raceService.cloneRace(this.cloneform).then((res) => {
        if (res && res.data.result === 0) {
          this.$message({
            message: "克隆任务成功",
            type: "success",
          });
          this.listRace();
        }
        this.cloneVisible = false;
      });
    },
    deleteResult(index, row) {
      // console.log(row)
      let data = {};
      data.id = row.id;
      raceService.deleteResult(data).then((res) => {
        if (res && res.data.result === 0) {
          this.$message({
            message: "清理赛事成绩成功",
            type: "success",
          });
          this.listRace();
        }
      });
    },
    async valid(index, row) {
      const { competitionid, matchid, amount, reportnum } = row;
      let res;
      if (!isDelta) {
        res = await fetch(
          `http://106.14.124.228:20181/api/v1/gugu.score.training.valid?matchId=${matchid}&competitionId=${competitionid}`
        );
      } else {
        res = await fetch(
          `http://106.14.124.228:20181/api/v1/gugu.score.training.valid?matchId=${matchid}&competitionId=${competitionid}&isDelta=1`
        );
      }

      res = await res.json();
      res = await res;
      let { count, scores, trainingmatch } = res;
      this.validVisible = true;

      let repeatArr = [];
      for (let i = 0; i < scores.length; i++) {
        repeatArr[i] = 0;
      }

      for (let score of scores) {
        let i = score.ranking;
        repeatArr[i] = ++repeatArr[i];
      }

      let repeatStr = "";
      let repeatCount = 0;
      repeatArr.filter((v, i) => {
        if (v > 1) {
          repeatStr += ` 第${i}名 重复${v}羽; `;
          repeatCount++;
        }
      });

      let missingScores = [];
      for (let score of scores) {
        missingScores[score.ranking - 1] = score;
      }
      let missingScores2 = [];
      for (let score of missingScores) {
        missingScores2.push(score);
      }
      scores = missingScores2;

      let missing = [];

      for (let i = 0; i < scores.length; i++) {
        missing[i] = i;
      }

      for (let score of scores) {
        if (score && score.ranking) {
          missing[score.ranking - 1] = null;
        }
      }

      let missingStr = "";
      let missStart = null;
      let tempMiss = null;
      let missCount = null;

      let missI = 0;
      for (let miss of missing) {
        missI++;
        if (missI == scores.length) {
          // 最后一个
          if (miss != null) {
            missCount++;
            if (missI == tempMiss + 1) {
              if (missCount > 1) {
                missingStr += ` ${missStart}-${
                  missStart + missCount - 1
                } 共${missCount}羽; `;
              } else {
                missingStr += ` ${missStart} `;
              }
            } else {
              missingStr += ` 第${missI}羽; `;
            }
            console.log("missI", missI);
          }
        } else {
          if (miss != null) {
            // 不存在
            if (tempMiss && missI == tempMiss + 1) {
              tempMiss++;
              missCount++;
            } else {
              missStart = missI;
              tempMiss = missI;
              missCount = 1;
            }
          } else {
            // 存在
            if (tempMiss && missI == tempMiss + 1) {
              if (missCount > 1) {
                missingStr += ` ${missStart}-${
                  missStart + missCount - 1
                } 共${missCount}羽; `;
              } else {
                missingStr += ` 第${missStart}羽; `;
              }
              console.log("missI", missI);
              missStart = null;
              tempMiss = null;
              missCount = null;
            }
          }
        }
      }
      repeatStr += `  共 ${repeatCount} 羽`;
      // window.open(
      //   `http://127.0.0.1:8001/#/BackValid?competitionId=${competitionid}&matchId=${matchid}`
      // );
      this.validData = {
        reportnum,
        count,
        missing: missingStr,
        repeat: repeatStr,
      };
    },
    downloadList(index, row) {
      if (row.jobstatus === 3) {
        this.$message({
          message: "异常记录无法进行下载",
          type: "error",
        });
        return;
      }
      window.open(baseUrl + "/race/download?id=" + row.id);
    },
    start2(index, row) {
      let dataInfo = {
        id: row.id,
      };
      race2Service.resumeRace(dataInfo).then((res) => {
        if (res && res.data.result === 0) {
          this.$message({
            message: "启动任务成功",
            type: "success",
          });
        }
        this.listRace();
      });
    },
    stop2(index, row) {
      let dataInfo = {
        id: row.id,
      };
      race2Service.stopRace(dataInfo).then((res) => {
        if (res && res.data.result === 0) {
          this.$message({
            message: "任务停止成功",
            type: "success",
          });
        }
        this.listRace();
      });
    },
    addRace() {
      this.addVisible = true;
      this.addform = {
        raceid: "",
        orgid: "",
        webid: 4,
        racename: "",
        racetype: "公棚",
        sftime: "",
        sfplace: "",
        sflng: "",
        sflat: "",
        sfdistance: "",
        sffeather: "",
        raceurl: "",
        frequency: "",
        endtime: "",
      };
      this.doOrgList();
    },
    doOrgList() {
      this.addform.orgid = "";
      sponsorService
        .matchOrganizers({ webid: this.addform.webid })
        .then((res) => {
          if (res && res.data.result === 0) {
            this.orgsels = res.data.data;
          }
        });
      // if (this.addform.webid == 2) {
      //   this.addform.raceurl = "http://gp.aj52.com/databd.aspx?ssid={id}";
      //   this.addform.raceid = "eW5odHNnX2IyMDIzMDkxNjE3NDYzMA%3d%3d";
      // } else if (this.addform.webid == 4) {
      //   this.addform.raceurl =
      //     "http://www.benzinglive.cn/AP_M1/AP0000_list.aspx?pid={id}";
      //   this.addform.raceid = "0190";
      // } else if (this.addform.webid == 6) {
      //   this.addform.raceurl = "http://www.ksxtkj.com/Join/Cote/Source/{id}";
      //   this.addform.raceid = "185c864f-cda5-4195-8e82-3f4c5f6fd235";
      // } else if (this.addform.webid == 13) {
      //   this.addform.raceurl = "http://speed.029019.cn/speed/{id}.html";
      //   this.addform.raceid = "T3_28034_23091701";
      // } else if (this.addform.webid == 88) {
      //   this.addform.raceurl = "请在下方填写完整的地址";
      //   this.addform.raceid = "";
      // }
      this.addform.raceurl = "";
    },
    addSubmit(addform) {
      let data = this.addform;
      if (!new RegExp("^\\d+$").test(data.sffeather)) {
        if (
          data.sffeather !== null &&
          data.sffeather !== "" &&
          data.sffeather !== undefined
        ) {
          this.$message({
            message: "参赛羽数只能为整数",
            type: "warning",
          });
          return;
        }
      }
      if (!new RegExp("^\\d+$").test(data.frequency)) {
        this.$message({
          message: "任务抓取频率只能为整数",
          type: "warning",
        });
        return;
      }
      raceService.addRace(this.addform).then((res) => {
        if (res && res.data.result === 0) {
          this.$message({
            message: "新增比赛成功",
            type: "success",
          });
          this.addVisible = false;
          this.listRace();
        }
      });
    },
    update(index, row) {
      // console.log(row)
      this.updateVisible = true;
      sponsorService
        .listOrganizers({ curpage: 1, pagesize: 9999 })
        .then((res) => {
          if (res && res.data.result === 0) {
            this.sponsors = res.data.data;
          }
        });
      this.updateform = {
        id: row.id,
        orgid: row.orgid,
        webid: row.webid,
        racename: row.racename,
        racetype: row.racetype,
        sftime: row.sftime,
        sfplace: row.sfplace,
        sflng: row.sflng,
        sflat: row.sflat,
        sfdistance: row.sfdistance,
        sffeather: row.sffeather,
        raceurl: row.raceurl,
        frequency: row.frequency,
        endtime: row.endtime,
        reportnum: row.reportnum,
      };
    },
    updateSubmit(updateform) {
      let data = this.updateform;
      if (!new RegExp("^\\d+$").test(data.sffeather)) {
        if (
          data.sffeather !== null &&
          data.sffeather !== "" &&
          data.sffeather !== undefined
        ) {
          this.$message({
            message: "参赛羽数只能为整数",
            type: "warning",
          });
          return;
        }
      }
      if (!new RegExp("^\\d+$").test(data.frequency)) {
        this.$message({
          message: "任务抓取频率只能为整数",
          type: "warning",
        });
        return;
      }
      raceService.updateRace(this.updateform).then((res) => {
        if (res && res.data.result === 0) {
          this.$message({
            message: i18n.t("tips.RACE.UPDATESUCCESS"),
            type: "success",
          });
          this.updateVisible = false;
          this.listRace();
        }
      });
    },
    // 变更上报方式
    changeReport(row) {
      let params = { id: row.id, reportstatus: row.reportstatus };
      raceService.updateReport(params).then((res) => {
        if (res && res.data.result === 0) {
          this.$message.success("操作成功!");
        } else {
          this.$message.error("操作失败！");
        }
        this.listRace();
      });
    },
    trans(data) {
      var returnstr = "";
      switch (data) {
        case 0:
          returnstr = i18n.t("status.NOTBEGIN");
          break;
        case 1:
          returnstr = i18n.t("status.RUNNING");
          break;
        case 2:
          returnstr = i18n.t("status.FINISHED");
          break;
        case 3:
          returnstr = i18n.t("status.EXCEPTION");
          break;
        case 4:
          returnstr = i18n.t("status.EXPIRED");
          break;
        case 5:
          returnstr = i18n.t("status.REPORT");
          break;
        default:
          break;
      }
      return returnstr;
    },
    enlarge() {
      if (this.width === "800px") {
        this.width = "1000px";
        this.iconImg = narrowImg;
      } else {
        this.width = "800px";
        this.iconImg = enlargeImg;
      }
    },
    doList() {
      // console.log(this.searchData.timerange);
      this.searchData.curpage = 1;
      this.listRace();
    },
    listRace() {
      if (this.searchData.timerange != null) {
        this.searchData.datebegin = this.searchData.timerange[0];
        this.searchData.dateend = this.searchData.timerange[1];
      } else {
        this.searchData.datebegin = "";
        this.searchData.dateend = "";
      }
      if (this.showInValid === true) {
        this.searchData.jobstatus2 = 1;
      } else {
        delete this.searchData.jobstatus2;
      }
      if (this.searchData.jobstatus != 3) this.searchData.joberror = "";
      this.searchData.racetype = "公棚";
      raceService.listRaces(this.searchData).then((res) => {
        if (res && res.data.result === 0) {
          this.races = res.data.data;
          this.searchData.total = res.data.total;
        }
      });
    },
    transStatus(data) {
      switch (data) {
        case 0:
          return "未开始";
        case 1:
          return "运行中";
        case 2:
          return "已完成";
        case 3:
          return "异常终止";
        case 4:
          return "已过期";
        case 5:
          return "已上报";
      }
      return "";
    },
    handleSizeChange(val) {
      this.searchData.pagesize = val;
      this.listRace();
    },
    handleCurrentChange(val) {
      this.searchData.curpage = val;
      this.listRace();
    },
    goto(type, webid, raceid) {
      this.$router.push({
        name: `${type}Link`,
        params: { webid: webid, raceid: raceid },
      });
    },
  },
};
</script>

<style>
.main_title {
  color: #343434;
  font-size: 18px;
  margin: 7px 0 0 0;
}

.area-detail {
  margin-top: 0px;
}

.define_label {
  line-height: 25px;
  text-align: left;
  display: block;
  margin-right: 10px;
  font-size: 14px;
  color: #565656;
  text-align: left;
  word-break: normal;
  width: 340px;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.define_span {
  line-height: 25px;
  text-align: right;
  display: block;
  margin-right: 10px;
  font-size: 14px;
  color: #565656;
  text-align: left;
  word-break: normal;
  width: 480px;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.message-back {
  width: 90%;
  /*height: 209px;*/
  background: rgba(233, 233, 233, 1);
  margin-left: 5%;
  margin-bottom: 10px;
}

.message-task {
  width: 90%;
  /*height: 209px;*/
  background: rgba(203, 225, 203, 1);
  margin-left: 5%;
  margin-bottom: 10px;
}

.joberror {
  width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.item {
  margin-top: 10px;
  padding-top: 5px;
  margin-right: 15px;
}
</style>
